const {
  rootPath,
  API,
  HomePath
} = require("../../utils/const")
const {
  postLogin,
  getRequest,
  requestUserInfo
} = require("../../utils/request")

// index.js
Page({
  data: {
    captchaImage: rootPath + API.captcha,
    captchaWidth: '100px',
    captchaHeight: '50px',
    loginForm: {},
    captchaImageData: ''
  },

  click: function () {


  },
  /*****************************/
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    // postRequest("captchaImage")
  },
  loadCaptcha: function () {
    this.setData({
      captchaImage: rootPath + API.captcha + "&" + Math.random()
    })
  },
  login: function (e) {
    console.log(e);
    const formValue = e.detail.value;
    const loginType = wx.getStorageSync('loginType');
    formValue.type = loginType;
    formValue.source = 'miniProgram';
    const {
      username, 
      password,
      code
    } = formValue;
    formValue.uuid = this.data.uuid;
    console.log(username, password, code, this.data.uuid);

    wx.showLoading({
      title: '正在登录,请稍后。。。',
    })
    postLogin(formValue).then(res => {
      // console.log(res)
      if (res.code === 200) {
        wx.setStorageSync('token', res.token)
        this.getUserInfo();
      } else {
        wx.showToast({
          title: res.msg,
          icon: "error"
        })
        this.captchLoad();
        wx.hideLoading();

      }
    })
  },
  getUserInfo: function () {
    requestUserInfo(HomePath)
  },
  captchLoad: function () {
    getRequest(API.captcha).then(res => {
      console.log("res", res);
      const {
        img,
        uuid
      } = res;
      if (img) {
        this.setData({
          captchaImageData: "data:image/gif;base64," + res.img,
          uuid: uuid
        })
      }
    });
    // console.log(e);
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.captchLoad();
    this.getUserInfo();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
})